<template>
  <el-container>
    <el-header>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" @submit.prevent>
        <el-form-item label="租户编码">
          <el-input
            v-model="searchForm.tenantCode"
            placeholder="租户编码" @keyup.enter="onSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="租户名称">
          <el-input
            v-model="searchForm.tenantName"
            placeholder="租户名称" @keyup.enter="onSearch"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="状态">
            <el-option label="启用" :value="true"></el-option>
            <el-option label="禁用" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="default" @click="onReset">重置</el-button>
          <el-button type="default" @click="onAddTenant" icon="CirclePlus">
            新增租户</el-button
          >
        </el-form-item>
      </el-form>
    </el-header>
    <el-divider direction="horizontal"></el-divider>
    <el-main class="cus-main">
      <el-table :data="tenantList" style="width: 100%">
        <el-table-column prop="id" label="ID" v-if="false"></el-table-column>
        <el-table-column prop="code" label="编码"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === true ? 'success' : 'danger'">
              {{ scope.row.status === true ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="countryCode"
          label="国家"
          v-if="false"
        ></el-table-column>
        <el-table-column
          prop="provinceCode"
          label="州/省"
          v-if="false"
        ></el-table-column>
        <el-table-column
          prop="cityCode"
          label="城市"
          v-if="false"
        ></el-table-column>
        <el-table-column
          prop="countyCode"
          label="区/县"
          v-if="false"
        ></el-table-column>
        <el-table-column
          prop="address"
          label="地址"
          v-if="false"
        ></el-table-column>
        <el-table-column prop="contact" label="联系人"></el-table-column>
        <el-table-column prop="phone" label="联系电话"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link type="primary" @click="onEdit(scope.row)"
              >编辑</el-button
            >
            <el-button link type="primary" @click="onDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="listTotal"
      >
      </el-pagination>
    </el-main>
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '修改租户' : '新增租户'"
      width="30%"
      header-class="dialog-custom-header"
    >
    <el-divider direction="horizontal" style="width: 95%"></el-divider>
    <el-form :model="newTenantForm" label-width="70px">
        <el-form-item label="编码">
          <el-input v-model="newTenantForm.code" :disabled="isEdit"></el-input>
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="newTenantForm.name"></el-input>
        </el-form-item>
        <el-form-item label="状态" v-if="isEdit">
          <el-select v-model="newTenantForm.status" placeholder="状态">
            <el-option label="启用" :value="true"></el-option>
            <el-option label="禁用" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="国家">
          <el-select
            v-model="newTenantForm.countryCode"
            placeholder="请选择国家"
          >
            <el-option
              v-for="country in countries"
              :key="country.code"
              :label="country.name"
              :value="country.code"
            />
          </el-select>
          <!-- <el-input v-model="newTenantForm.countryCode"></el-input> -->
        </el-form-item>
        <el-form-item label="州/省">
          <el-select
            v-model="newTenantForm.provinceCode"
            placeholder="请选择州/省"
          >
            <el-option
              v-for="province in provinces"
              :key="province.code"
              :label="province.name"
              :value="province.code"
            />
          </el-select>
          <!-- <el-input v-model="newTenantForm.provinceCode"></el-input> -->
        </el-form-item>
        <el-form-item label="城市">
          <el-select v-model="newTenantForm.cityCode" placeholder="请选择城市">
            <el-option
              v-for="city in cities"
              :key="city.code"
              :label="city.name"
              :value="city.code"
            />
          </el-select>
          <!-- <el-input v-model="newTenantForm.cityCode"></el-input> -->
        </el-form-item>
        <el-form-item label="区/县">
          <el-select
            v-model="newTenantForm.countyCode"
            placeholder="请选择区/县"
          >
            <el-option
              v-for="county in counties"
              :key="county.code"
              :label="county.name"
              :value="county.code"
            />
          </el-select>
          <!-- <el-input v-model="newTenantForm.countyCode"></el-input> -->
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="newTenantForm.address"></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="newTenantForm.contact"></el-input>
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="newTenantForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { ref, reactive, onMounted, watch } from "vue";
import { get, post, put, del } from "@/utils/request";
import { ddicStore } from "@/store/ddic";
import { storeToRefs } from "pinia";

const dialogVisible = ref(false);
const isEdit = ref(false); // 是否为修改模式
const currentEditId = ref(null); // 当前编辑的租户ID
const searchForm = reactive({
  tenantCode: null,
  tenantName: null,
  status: null,
});
const newTenantForm = reactive({
  code: "",
  name: "",
  status: true,
  countryCode: "",
  provinceCode: "",
  cityCode: "",
  countyCode: "",
  address: "",
  contact: "",
  phone: "",
});
const tenantList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const listTotal = ref(0);

const ddic = ddicStore();
const { regions } = storeToRefs(ddic);
// console.log(regions.value)
const countries = ref([]); // 国家数据
const provinces = ref([]); // 省份数据
const cities = ref([]); // 城市数据
const counties = ref([]); // 区县数据

watch(
  () => newTenantForm.countryCode,
  (newCode, oldCode) => {
    if (newCode) {
      // const selectedProvinces = countries.value.filter(
      //   (region) => region.parent === newCode
      // );
      let country = countries.value.find(
        (c) => c.code === newCode
      );
      provinces.value = country.children;
      if (oldCode) {
        newTenantForm.provinceCode = "";
        newTenantForm.cityCode = "";
        newTenantForm.countyCode = "";
      }
      cities.value = []; // 清空城市数据
      counties.value = []; // 清空区县数据
    }
  }
);
watch(
  () => newTenantForm.provinceCode,
  (newCode, oldCode) => {
    if (newCode) {
      // const selectedCities = regions.value.filter(
      //   (region) => region.parent === newCode
      // );
      let province = provinces.value.find(
        (p) => p.code === newCode
      );
      cities.value = province.children;
      if (oldCode) {
        newTenantForm.cityCode = "";
        newTenantForm.countyCode = "";
      }
      counties.value = []; // 清空区县数据
    }
  }
);

watch(
  () => newTenantForm.cityCode,
  (newCode, oldCode) => {
    if (newCode) {
      let city = cities.value.find(
        (c) => c.code === newCode
      );
      counties.value = city.children;
      // const selectedCounties = regions.value.filter(
      //   (region) => region.parent === newCode
      // );
      // counties.value = selectedCounties;
      if (oldCode) {
        newTenantForm.countyCode = "";
      }
    }
  }
);

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};
const onSearch = () => {
  // 实现搜索逻辑
  // console.log("搜索条件:", searchForm);
  let params = {
    code: searchForm.tenantCode,
    name: searchForm.tenantName,
    status: searchForm.status,
    page: currentPage.value,
    size: pageSize.value,
  };
  get("/tmo/tenants", params)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        tenantList.value = res.data.data.data;
        listTotal.value = res.data.data.total;
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onAddTenant = () => {
  isEdit.value = false;
  Object.keys(newTenantForm).forEach((key) => {
    if (key === "status") {
      newTenantForm[key] = true;
    } else {
      newTenantForm[key] = "";
    }
  });
  dialogVisible.value = true;
};
const onReset = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = null;
  });
};
const onEdit = (row) => {
  // 初始化列表
  isEdit.value = true;
  currentEditId.value = row.id;
  // Object.keys(newTenantForm).forEach((key) => {
  //   newTenantForm[key] = null;
  // });
  Object.assign(newTenantForm, row);
  if (newTenantForm.cityCode) {
    const selectedCounties = regions.value.filter(
      (region) => region.parent === newTenantForm.cityCode
    );
    counties.value = selectedCounties;
  }
  dialogVisible.value = true;
};

const onDelete = (row) => {
  del("/tmo/tenants/" + row.id)
    .then((res) => {
      // console.log("搜索结果:", res);
      if (res.data.code === 0) {
        tenantList.value = tenantList.value.filter(
          (item) => item.id !== row.id
        );
        ElMessage.success("删除成功");
      } else if (res.data.code === 401) {
        sessionStorage.clear();
        window.location.assign("/login");
      } else {
        ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
      }
    })
    .catch((e) => {
      ElMessage.error(e.message);
    });
};

const onSubmit = async () => {
  let succ = false;
  if (isEdit.value) {
    // 修改租户逻辑
    const index = tenantList.value.findIndex(
      (item) => item.id === currentEditId.value
    );
    if (index !== -1) {
      tenantList.value[index] = {
        ...newTenantForm,
        id: currentEditId.value,
      };
    }
    let payload = {
      name: newTenantForm.name,
      status: newTenantForm.status,
      countryCode: newTenantForm.countryCode,
      provinceCode: newTenantForm.provinceCode,
      cityCode: newTenantForm.cityCode,
      countyCode: newTenantForm.countyCode,
      address: newTenantForm.address,
      contact: newTenantForm.contact,
      phone: newTenantForm.phone,
    };
    await put("/tmo/tenants/" + currentEditId.value, payload)
      .then((res) => {
        // console.log("搜索结果:", res);
        if (res.data.code === 0) {
          onSearch();
          succ = true;
          ElMessage.success("更新成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  } else {
    // 后端写入
    let payload = {
      code: newTenantForm.code,
      name: newTenantForm.name,
      countryCode: newTenantForm.countryCode,
      provinceCode: newTenantForm.provinceCode,
      cityCode: newTenantForm.cityCode,
      countyCode: newTenantForm.countyCode,
      address: newTenantForm.address,
      contact: newTenantForm.contact,
      phone: newTenantForm.phone,
    };
    await post("/tmo/tenants", payload)
      .then((res) => {
        // console.log("搜索结果:", res);
        if (res.data.code === 0) {
          tenantList.value.push({
            ...newTenantForm,
            id: res.data.data.id,
          });
          // onSearch();
          succ = true;
          ElMessage.success("新增成功");
        } else if (res.data.code === 401) {
          sessionStorage.clear();
          window.location.assign("/login");
        } else {
          ElMessage.error(res.data.msg ? res.data.msg : res.data.message);
        }
      })
      .catch((e) => {
        ElMessage.error(e.message);
      });
  }
  if (succ) {
    dialogVisible.value = false;
  }
};
onMounted(() => {
  // 初始化国家下拉列表
  for (const region of regions.value) {
    if (region.level === 1) {
      countries.value.push(region);
    }
  }
  onSearch();
});
</script>
